//package cn.edu.lingnan.filter;
//
//import cn.edu.lingnan.context.BaseContext;
//import cn.edu.lingnan.user.dtos.Result;
//import cn.edu.lingnan.utils.JwtUtils;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import io.jsonwebtoken.Claims;
//import jakarta.servlet.FilterChain;
//import jakarta.servlet.ServletException;
//import jakarta.servlet.http.HttpServletRequest;
//import jakarta.servlet.http.HttpServletResponse;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
//import org.springframework.security.core.context.SecurityContextHolder;
//import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
//import org.springframework.util.StringUtils;
//import org.springframework.web.filter.OncePerRequestFilter;
//
//import java.io.IOException;
//import java.util.Collections;
//
//@Slf4j
//public class JwtAuthenticationFilter extends OncePerRequestFilter {
//
//    @Override
//    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
//            throws ServletException, IOException {
//
//        String url = request.getRequestURL().toString();
//        log.info("请求 URL: {}", url);
//
//        // 放行登录、注册、验证码等接口
//        if (url.contains("login") || url.contains("register") || url.contains("verify") || url.contains("captcha")) {
//            filterChain.doFilter(request, response);
//            return;
//        }
//
//        String jwt = request.getHeader("Authorization");
//        log.info("Token: {}", jwt);
//
//        if (jwt != null && jwt.startsWith("Bearer ")) {
//            jwt = jwt.substring(7); // 移除 "Bearer " 前缀
//        }
//
//        if (!StringUtils.hasLength(jwt)) {
//            log.info("令牌为空");
//            unauthorizedResponse(response, "没有登录");
//            return;
//        }
//
//        // 验证令牌
//        try {
//            Claims claims = JwtUtils.parseJWT(jwt);
//            Integer userId = Integer.valueOf(claims.get("userId").toString());
//            BaseContext.setCurrentId(userId);
//
//            log.info("当前用户 ID: {}", userId);
//
//            // 将用户信息存入 SecurityContext，供后续认证流程使用
//            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
//                    userId, null, Collections.emptyList());
//            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
//            SecurityContextHolder.getContext().setAuthentication(authentication);
//
//        } catch (Exception e) {
//            log.error("无法解析令牌", e);
//            unauthorizedResponse(response, "令牌无效");
//            return;
//        }
//
//        filterChain.doFilter(request, response);
//    }
//
//    private void unauthorizedResponse(HttpServletResponse response, String message) throws IOException {
//        response.setContentType("application/json");
//        response.setCharacterEncoding("UTF-8");
//        Result error = Result.unauthorized(message);
//        String notLogin = new ObjectMapper().writeValueAsString(error);
//        response.getWriter().write(notLogin);
//    }
//}
